﻿namespace Vcare.Controllers
{
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Data.Entity;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  using Vcare.Models;
  using Vcare.DAL;
  using Vcare.ViewModels;
  using Vcare.Helpers;
  using System.Web.Security;
  using Vcare.Properties;
  using System.Data.Entity.Validation;
  using System.Globalization;
using System.Configuration;

    [Authorize]
    public class MembersController : Controller
    {
        private VcareContext db = new VcareContext();

        public ActionResult Index()
        {
          Guid userID = (Guid)Membership.GetUser().ProviderUserKey;
          UserInfo userInfo = db.UserInfo.Where(m => m.UserID == userID).FirstOrDefault();
          int userLevel = db.Authority.Find(userInfo.AuthorityID).Level;
          int cc = db.UserInfo.Where(m => m.UserID == userID).FirstOrDefault().CallCentreID ?? 0;
          switch (userLevel)
          {
            case 1:
              DateTime dateCheck = DateTime.Now.AddDays(-3);
              return View(db.Members.Where(m => m.Paid==null).Where(m => m.DateUpdated>dateCheck).ToList());
            case 2:
              return View(db.Members
                .Where(m => m.CallCentreID == cc)
                .Where(m => m.Processed==null || m.Processed==false)
                .OrderByDescending(o => o.ContactDate)
                .ToList());
            case 3:
              return View(db.Members
                .Where(m => m.CallCentreID == cc && m.Paid==null)
                .Where(m => m.Processed == null || m.Processed == false)
                .OrderByDescending(o => o.ContactDate)
                .ToList());
            case 5:
              return View(db.Members
                .Where(m => m.CallCentreID == cc && m.QAd == null)
                .Where(m => m.Processed == null || m.Processed == false)
                .OrderByDescending(o => o.ContactDate)
                .ToList());
            default:
              break;
          }
          return View();
        }

        public ActionResult Details(int id = 0)
        {
            Members members = db.Members.Find(id);
            if (members == null)
            {
                return HttpNotFound();
            }
            return View(members);
        }

        //
        // GET: /Members/Create

        public ActionResult Create()
        {
          Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
          CallCentres cc = db.UserInfo
              .Join(db.CallCentres, a => a.CallCentreID, b => b.CallCentreID, (a, b) => new { a, b })
              .Where(m => m.a.UserID == currentUser)
              .Select(s => s.b)
              .FirstOrDefault();
          AppLists myLists = new AppLists();
          myLists.PopulateLists(cc.CallCentreID);
          ViewBag.Title=new SelectList(db.Salutations,"Salutation","Salutation");
          ViewBag.PaymentType = new SelectList(myLists.ListPaymentType, "PaymentType", "PaymentType");
          List<SelectListItem> pricePlanItems = new List<SelectListItem>();

          ViewBag.PricePlan = new SelectList(myLists.PricePlan, "Value", "Text");
          ViewBag.PaymentOption=new SelectList(myLists.PaymentOption);
          ViewBag.CardType = new SelectList(myLists.CardType, "Value", "Text");
          Members member = new Members();        
          return View(member);
        }

        [HttpPost]
        public ActionResult Create(Members member)
        {
          if (ModelState.IsValid)
          {
            // determine the next index number
            string todaysDate = DateTime.Now.ToString("ddMMyy");
            int nextIndex = 1;
            if (db.Members.Where(m => m.MembershipID.Contains(todaysDate)).Count() != 0)
            {
              string memberIndex = db.Members
                          .Where(m => m.MembershipID.Contains(todaysDate))
                          .OrderByDescending(m => m.MembershipID.Substring(m.MembershipID.Length - 3))
                          .FirstOrDefault()
                          .MembershipID;
              nextIndex = Convert.ToInt16(memberIndex.Substring(memberIndex.Length - 3)) + 1;
            }
            AppLists myLists = new AppLists();
            myLists.PopulateLists();
            Guid newID = (Guid)Membership.GetUser().ProviderUserKey;
            int? callCentreid = db.CallCentres.Find(db.UserInfo.Where(m => m.UserID == newID).FirstOrDefault().CallCentreID).CallCentreID;
            member.MembershipID = db.CallCentres.Find(callCentreid).ccsuffix.Trim() + DateTime.Now.ToString("ddMMyy") + nextIndex.ToString().PadLeft(3, '0');
            member.CallCentreID = callCentreid;

            member = CheckVals(member);
            member = MemberPricePlan(member);

            member.DateUpdated = DateTime.Now;
            db.Members.Add(member);
            try
            {
                db.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
              List<string> errorReport = new List<string>();
              foreach (var eve in e.EntityValidationErrors)
              {
                errorReport.Add(string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
                foreach (var ve in eve.ValidationErrors)
                {
                  errorReport.Add(string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage));
                }
              }
              return View("UploadErrors", errorReport);
            }
            return RedirectToAction("Index");
          }
          else
          {
            List<string> errorReport = new List<string>();
            foreach (ModelState modelState in ViewData.ModelState.Values)
            {
              foreach (ModelError error in modelState.Errors)
              {
                errorReport.Add(error.ErrorMessage);
              }
            }
            return View("Errors",errorReport);
          }

        }

        public Members CheckVals(Members member)
        {

          if (member.PaymentType == "Direct Debit")
          {
            member.CardHoldersName = null;
            member.CVCNumber = null;
            member.StartDate = null;
            member.IssueNumber = null;
            member.CardHoldersName = null;
            member.CardNumber = null;
            member.CardType = null;
            member.ExpiryDate = null;
          }
          else
          {
            member.AccountNo = null;
            member.AccountName = null;
            member.Sortcode = null;
            member.CVCNumber = member.CardType;
          }
          return member;
        }

      public Members MemberPricePlan(Members member)
      {
        Guid currentUser = (Guid)Membership.GetUser().ProviderUserKey;
        CallCentres cc = db.UserInfo
        .Join(db.CallCentres, a => a.CallCentreID, b => b.CallCentreID, (a, b) => new { a, b })
        .Where(m => m.a.UserID == currentUser)
        .Select(s => s.b)
        .FirstOrDefault();
        AppLists myLists = new AppLists();
        myLists.PopulateLists(cc.CallCentreID);
        // does it exist in the Rates table
        decimal iPP = Convert.ToDecimal(member.PricePlan) ;
        if (db.Rates.Any(m => m.CallCentreID==cc.CallCentreID && m.Fee==iPP))
        {
          Rates rate = db.Rates.Where(m => m.CallCentreID == cc.CallCentreID && m.Fee == iPP).FirstOrDefault();
          member.PricePlan = rate.Description;
          member.ValueOfSinglePayment = iPP;
        }
        else
        {

          member.PricePlan = myLists.PricePlan.Where(m => m.Value == member.PricePlan).FirstOrDefault().Text;
          member.ValueOfSinglePayment = Convert.ToDecimal(myLists.PricePlan.Where(m => m.Text == member.PricePlan).FirstOrDefault().Value);
        }
        return member;
    }

        public ActionResult Edit(int id = 0)
        {
            Members members = db.Members.Find(id);
            AppLists myLists = new AppLists();
            myLists.PopulateLists();
            ViewBag.Titles = new SelectList(db.Salutations, "Salutation", "Salutation", members.Title);
            ViewBag.PaymentType = new SelectList(myLists.ListPaymentType,"PaymentType","PaymentType", members.PaymentType);
            ViewBag.PricePlan = new SelectList(myLists.PricePlan, "Value", "Text",members.PricePlan);
            ViewBag.PaymentOption = new SelectList(myLists.PaymentOption);
            ViewBag.CardType = new SelectList(myLists.CardType, "Value", "Text");
            if (members == null)
            {
                return HttpNotFound();
            }
            return View(members);
        }


        [HttpPost]
        public ActionResult Edit(Members members)
        {
            if (ModelState.IsValid)
            {
              members = CheckVals(members);
              members = MemberPricePlan(members);
              members.DateUpdated = DateTime.Now;
              db.Entry(members).State = EntityState.Modified;
              db.SaveChanges();
              return RedirectToAction("Index");
            }
            return View(members);
        }


        public ActionResult Delete(int id = 0)
        {
            Members members = db.Members.Find(id);
            if (members == null)
            {
                return HttpNotFound();
            }
            return View(members);
        }

        //
        // POST: /Members/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Members members = db.Members.Find(id);
            db.Members.Remove(members);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        public ActionResult Checkout(int id)
        {
          Members member = db.Members.Find(id);
          member.Paid = true;
          member.DateOfPayment = DateTime.Now;
          db.SaveChanges();
          //ViewBag.Fullname = string.Format("{0} {1}", db.Members.Find(id).Firstname, db.Members.Find(id).Lastname);
          //Session["id"] = id;
          //return View();
          return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }

        [HttpGet]
        public JsonResult CheckTPSNumber(string telephoneNumber)
        {
          string retVal = string.Empty;
          if (telephoneNumber.Substring(0,1)!="0")
          {
            telephoneNumber = "0" + telephoneNumber ;
          }

          if (db.TPSdata.Any(m => m.Telephone==telephoneNumber))
          {
            retVal="Fail";
          }
          else
          {
            if (db.Members.Any(m => m.Phone == telephoneNumber) || db.Members.Any(m => m.Phone.Substring(1)==telephoneNumber) || db.Members.Any(m => m.Phone==telephoneNumber.Substring(1)))
            {
              retVal = "Fail";
            }
            else
            {
              retVal = "Success";
            }
          }
          return Json(retVal, JsonRequestBehavior.AllowGet);

        }
    }
}